//
//  YWDoTempDeteAndUpKeepEquTypeMissionTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 2017/4/27.
//  Copyright © 2017年 ewin. All rights reserved.
//

#import "YWDoTempDeteAndUpKeepEquTypeMissionTableViewController.h"
#import "YWPostTroubleTableViewController.h"
#import "YWShowPostTroubleInfoTableViewController.h"
#import "YWDoTempDeteAndUpKeepMissionTableViewController.h"

#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWCommonTool.h"
#import "MBProgressHUD.h"
#import "YWConst.h"
#import "YWLoginTool.h"

#import "YWDoEquipmentMissionCell.h"
#import "YWPostTroubleInfoCell.h"

#import "YWEquipmentManager.h"
#import "YWEquipment.h"
#import "YWReportTroubleManager.h"
#import "YWReportTroubleModel.h"
#import "YWDBTool.h"
#import "YWDetectAndUpkeepManager.h"
#import "YWMissionManager.h"
#import "YWResourceManager.h"
#import "YWBuildingManager.h"
#import "YWBuilding.h"
#import "YWEquipmentType.h"
#import "YWEquipmentFieldRecord.h"

@interface YWDoTempDeteAndUpKeepEquTypeMissionTableViewController ()<YWDoEquipmentMissionCellDelegate,YWPostTroubleVCDelegate,clickCancelThePostTroubleMissionDelegate>

@property (nonatomic, strong) UIView* footView;
@property (nonatomic, strong) UIButton* myTroublesButton;
@property (nonatomic, strong) UIButton* submitButton;
@property (nonatomic, weak) MBProgressHUD* HUD;

@property (nonatomic, strong) NSArray* allEquipments;
@property (nonatomic, strong) NSMutableArray* recordEquipmentIds;
//设备报障数组
@property (nonatomic, strong) NSMutableArray *postTroubleRecordArray;
@property (nonatomic, strong) NSMutableArray * saveEquipmentArray;
@property (nonatomic, strong) NSMutableArray * allEquTypeArray;
//扫描进入任务页面时的时间
@property (nonatomic, assign) NSTimeInterval clientScanTime;
@property (nonatomic, strong) NSMutableArray * redBorderArray;
@end

@implementation YWDoTempDeteAndUpKeepEquTypeMissionTableViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *typeName = [YWCommonTool maintenanceTypeOfMaintenanceTypeId:self.maintenanceType];
    self.title = typeName;
    _clientScanTime = [[NSDate date] timeIntervalSince1970]*1000;
    [self setupTableView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //是为了让变红的cell的边框消失
    [self.tableView reloadData];
}

- (void)setupTableView{
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = self.footView;
    
    [self.tableView setEditing:YES];
    self.tableView.allowsSelectionDuringEditing=YES;
    
    [self.tableView registerClass:[YWDoEquipmentMissionCell class] forCellReuseIdentifier:YWDoEquipmentMissionCellIdentifier];
}

- (void)setMaintenanceType:(YWMaintenanceType)maintenanceType{
    _maintenanceType = maintenanceType;
    _allEquipments = nil;
    if (self.allEquArray) {
        _allEquipments = self.allEquArray;
    }else if (_qrCodeId) {
        _allEquipments = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:_qrCodeId];
    }else if (_locationId){
        _allEquipments = [[YWEquipmentManager shareManager] equipmentWithLocationId:_locationId];
    }
    //自动保存设备
    [self.saveEquipmentArray addObjectsFromArray:_allEquipments];
    
    _allEquTypeArray = [NSMutableArray array];
    __block NSInteger lastEquipmentTypeId = 0;
    __block NSMutableArray *array = nil;
    [_allEquipments enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
//        if (_currentEquipmentId && [equipment.equipmentId isEqualToString:_currentEquipmentId]) {
//            _currentEquipment = equipment;
//        }
        //按照设备类型分组
        NSInteger equipmentTypeId = equipment.equipmentTypeId;
        if (lastEquipmentTypeId==0 || equipmentTypeId !=lastEquipmentTypeId) {
            lastEquipmentTypeId = equipmentTypeId;
            array = [NSMutableArray array];
        }
        [array addObject:equipment];
        if (![_allEquTypeArray containsObject:array] && array.count) {
            [_allEquTypeArray addObject:array];
        }
        
        NSArray *runTimeParameterArray = [[YWEquipmentManager shareManager] equipmentFieldsWithTypeId:equipment.equipmentTypeId maintenanceTypeId:maintenanceType];
        equipment.runTimeParameterArray = runTimeParameterArray.count?runTimeParameterArray:nil;
    }];
//    if (_currentEquipment==nil && _allEquipments.count) {
//        _currentEquipment = _allEquipments[0];
//    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return _allEquTypeArray.count;
    }else{
        return _postTroubleRecordArray.count ?: 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        YWDoEquipmentMissionCell *cell = [tableView dequeueReusableCellWithIdentifier:YWDoEquipmentMissionCellIdentifier];
        cell.delegate = self;
        cell.equipmentArray = self.allEquTypeArray[indexPath.row];
        if ([self.redBorderArray containsObject:@(indexPath.row)]) {
            cell.layer.borderWidth = 1.0;
            cell.layer.borderColor = [UIColor customRedColor].CGColor;
        }else{
            cell.layer.borderColor = [UIColor whiteColor].CGColor;
            cell.layer.borderWidth = 0;
        }
        return cell;
    }else{
        YWPostTroubleInfoCell* cell = [YWPostTroubleInfoCell cellWithTableView:tableView];
        YWReportTroubleModel * reportTrouble = _postTroubleRecordArray.count > 0 ? _postTroubleRecordArray[indexPath.row] : nil;
        cell.reportTrouble = reportTrouble;
        return cell;
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString* HeaderIdentifier = @"YWDoEquipmentInspMissionTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSString* headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

- (NSString*)titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return NSLocalizedString(@"selectEquipment", nil);//@"选择设备";
    }else{
        return NSLocalizedString(@"postTroubleEquipment", nil);//@"报障设备";
    }
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        return self.postTroubleRecordArray.count ? 58 :44;
    }else{
        return 58;
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        NSArray * equTypeArray = _allEquTypeArray[indexPath.row];
        [equTypeArray enumerateObjectsUsingBlock:^(YWEquipment *     _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
            NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %@", @"equipmentId", equipment.equipmentId];
            NSArray *array = [[self.saveEquipmentArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
            if (array.count>0) {
                [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
                *stop = YES;
            }else{
                [tableView deselectRowAtIndexPath:indexPath animated:NO];
            }
        }];
    }
    
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return indexPath.section == 0 ? YES : NO;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        NSArray * equTypeArray = _allEquTypeArray[indexPath.row];
        [self.saveEquipmentArray addObjectsFromArray:equTypeArray];
    }else{
        YWReportTroubleModel * reportTrouble = _postTroubleRecordArray.count>0?_postTroubleRecordArray[indexPath.row]:nil;
        if (reportTrouble) {
            YWShowPostTroubleInfoTableViewController *showPostTroubleVC = [[YWShowPostTroubleInfoTableViewController alloc] init];
            showPostTroubleVC.reportTrouble = reportTrouble;
            showPostTroubleVC.delegate = self;
            [self.navigationController pushViewController:showPostTroubleVC animated:YES];
        }
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        NSArray * equTypeArray = _allEquTypeArray[indexPath.row];
        [self.saveEquipmentArray removeObjectsInArray:equTypeArray];
    }
}

- (UIView*)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 100);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH/2-20*2;
        //      报障
        _myTroublesButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _myTroublesButton.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        _myTroublesButton.layer.masksToBounds = YES;
        _myTroublesButton.layer.cornerRadius = 5.0;
        
        [_myTroublesButton setTitle:NSLocalizedString(@"postTrouble", nil) forState:UIControlStateNormal];
        [_myTroublesButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _myTroublesButton.backgroundColor = [UIColor customRedColor];
        [_myTroublesButton addTarget:self action:@selector(cliclPostTroubleEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:_myTroublesButton];
        //      提交
        _submitButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _submitButton.frame = CGRectMake(20*2+_myTroublesButton.bounds.size.width+20, 30, buttonWidth, kButtonH);
        _submitButton.layer.masksToBounds = YES;
        _submitButton.layer.cornerRadius = 5.0;
        
        [_submitButton setTitle:NSLocalizedString(@"commit", nil) forState:UIControlStateNormal];
        [_submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _submitButton.backgroundColor = [UIColor customBlueColor];
        [_submitButton addTarget:self action:@selector(clickCommintButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:_submitButton];
        
    }
    return _footView;
}

- (NSMutableArray *)saveEquipmentArray{
    if (!_saveEquipmentArray) {
        _saveEquipmentArray = [NSMutableArray array];
    }
    return _saveEquipmentArray;
}
- (NSMutableArray *)redBorderArray{
    if (!_redBorderArray) {
        _redBorderArray = [NSMutableArray array];
    }
    return _redBorderArray;
}

#pragma mark - YWDoEquipmentMissionCellDelegate event
- (void)clickLabelEvent:(UITableViewCell *)cell{
    //代理点击事件
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(YWDoEquipmentMissionCell*)cell];
    YWDoTempDeteAndUpKeepMissionTableViewController * equTempDeteAndUpKeepMissionVC = [[YWDoTempDeteAndUpKeepMissionTableViewController alloc] init];
    equTempDeteAndUpKeepMissionVC.maintenanceType = self.maintenanceType;
    equTempDeteAndUpKeepMissionVC.qrCodeId = self.qrCodeId;
    equTempDeteAndUpKeepMissionVC.locationId = self.locationId;
    equTempDeteAndUpKeepMissionVC.allEquArray = self.allEquArray;
    equTempDeteAndUpKeepMissionVC.allEquipments = self.allEquTypeArray[indexPath.row];
    equTempDeteAndUpKeepMissionVC.saveEquipmentArray = self.saveEquipmentArray;
    equTempDeteAndUpKeepMissionVC.tempDeteAndUpKeepEquTypeVC = self;
    [self.navigationController pushViewController:equTempDeteAndUpKeepMissionVC animated:YES];
    [self.redBorderArray removeAllObjects];
}

#pragma mark - clickCancelThePostTroubleMissionDelegate
- (void)clickCancelTheReportTrouble:(YWReportTroubleModel*)reportTrouble{
    if ([_postTroubleRecordArray containsObject:reportTrouble]) {
        [[YWReportTroubleManager shareManager] deleteReportTroubleWithTroubleId:reportTrouble.troubleId orUniqueTag:reportTrouble.uniqueTag];
        [_postTroubleRecordArray removeObject:reportTrouble];
        [self.tableView reloadData];
    }
}

#pragma mark - buttonAction
- (void)cliclPostTroubleEvent:(UIButton*)sender{
    //报障
    NSArray *allEquipmentArray = nil;
    if (_allEquArray) {
        allEquipmentArray = self.allEquArray;
    }else if (_qrCodeId) {
        allEquipmentArray = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:_qrCodeId];
    }else if (_locationId){
        allEquipmentArray = [[YWEquipmentManager shareManager] equipmentWithLocationId:_locationId];
    }
    
    YWPostTroubleTableViewController * postTroublevc = [[YWPostTroubleTableViewController alloc] init];;
    postTroublevc.currentEquipment = allEquipmentArray.count ? allEquipmentArray[0] : nil;
    postTroublevc.equipmentArray = allEquipmentArray;
    postTroublevc.qrCodeId = _qrCodeId;
    postTroublevc.locationId = _locationId;
    postTroublevc.shouldPopBack = YES;
    postTroublevc.delegate = self;
    [self.navigationController pushViewController:postTroublevc animated:YES];
}

#pragma mark - YWPostTroubleVCDelegate
- (void)passBackReportTrouble:(YWReportTroubleModel*)reportTrouble{
    //报修记录
    if (!_postTroubleRecordArray) {
        _postTroubleRecordArray = [NSMutableArray array];
    }
    if (reportTrouble) {
        [_postTroubleRecordArray addObject:reportTrouble];
        [self.tableView reloadData];
    }
}
- (void)clickCommintButtonEvent:(UIButton*)sender{
    
    if (_saveEquipmentArray.count==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"saveMaintenanceRecordBeforeCommit", nil)];
        return;
    }
    __block BOOL isRequire = YES;
    __block NSString *reasonable = nil;
    __block BOOL containEmoji = NO;
    [self.saveEquipmentArray enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger equIdx, BOOL * _Nonnull stop) {
        if ([YWCommonTool isContainsEmoji:equipment.psText] ) {
            containEmoji = YES;
            *stop = YES;
        }
        [equipment.runTimeParameterArray enumerateObjectsUsingBlock:^(YWRunTimeParameter*  _Nonnull field, NSUInteger cusIdx, BOOL * _Nonnull fieldStop) {
            if (field.required && field.fieldValue.length==0 && field.fieldOptionValue ==nil) {
                [self.allEquTypeArray enumerateObjectsUsingBlock:^(NSArray *  _Nonnull array, NSUInteger idx, BOOL * _Nonnull arrayStop) {
                    YWEquipment * equ = array.count?array[0]:nil;
                    if (equ.equipmentTypeId == equipment.equipmentTypeId) {
                        [self.redBorderArray addObject:@(idx)];
                        isRequire = NO;
                        *fieldStop = YES;
                        *stop = YES;
                        *arrayStop = YES;
                    }
                }];
            }
            if (field.fieldType.fieldTypeId==YWEquipmentFieldTypeIdNumber && (field.maxFieldValue!=0 || field.minFieldValue!=0) && field.fieldValue.length>0 && ([field.fieldValue integerValue]>field.maxFieldValue||[field.fieldValue integerValue]<field.minFieldValue)) {
                reasonable = field.fieldName;
                //*fieldStop = YES;
            }
            if ([YWCommonTool isContainsEmoji:field.fieldValue]){
                containEmoji = YES;
                *stop = YES;
            }
        }];
    }];
    if (!isRequire) {
        [self.tableView reloadData];
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"isRequired", nil)];
        return;
    }
    if (containEmoji) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (reasonable.length>0) {
        NSString *tips = [NSString stringWithFormat:@"%@%@",reasonable,NSLocalizedString(@"valueNotInReasonableRangeAndMakeSureToCommit", nil)];
        
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:tips preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self commitRecord];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        [self commitRecord];
    }
}

- (void)commitRecord{
    NSString* content = [NSString stringWithFormat:NSLocalizedString(kTextConfirmSubmitMission, nil)];
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:content preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.HUD show:YES];
        //上传报障
        [self.postTroubleRecordArray enumerateObjectsUsingBlock:^(YWReportTroubleModel*  _Nonnull reportTrouble, NSUInteger idx, BOOL * _Nonnull stop) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSArray *troublePicureArray = [[YWDBTool shareDBTool] picturesWithMissionId:reportTrouble.troubleId maintenanceType:reportTrouble.maintenanceTypeId];
                //                [[YWMissionManager shareManager] startUploadRecords:nil Mission:reportTrouble pictures:troublePicureArray];
                [[YWReportTroubleManager shareManager] startUploadReportTrouble:reportTrouble pictures:troublePicureArray];
            });
        }];
        
        [_saveEquipmentArray enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
            YWMaintenanceMission *maintenanceMission = [self createTempMaintenanceMissionWithType:self.maintenanceType];
            maintenanceMission.equipmentTypeId = equipment.equipmentTypeId;
            
            __block YWEquipmentMaintenanceRecord* record = [self createEquipmentMaintenanceRecordsWithMission:maintenanceMission equipment:equipment];
            __block NSArray* pictures = [self createPictureWithMission:maintenanceMission equipment:equipment record:record];
            __block NSArray* equipmentFields = [self createEquipmentFieldsRecordsWithRecord:record equipment:equipment];
            
            //            if (maintenanceMission.maintenanceTypeId == YWMaintenanceTypeDetection) {
            //                [[YWEquipmentManager shareManager] updateLastMaintenanceTimeWithEquipments:_saveEquipmentArray maintenceTime:maintenanceMission.finishTime executorName:[YWLoginTool loginUser].userName];
            //            }
            
            BOOL saveMission = [YWDetectAndUpkeepManager updateDetectAndUpkeepMissionWithArray:maintenanceMission? @[ maintenanceMission ] : nil];
            BOOL saveMaintenanceRecord = [YWDetectAndUpkeepManager updateMaintenanceRecords:record?@[record]:nil maintenanceTypeId:maintenanceMission.maintenanceTypeId];
            BOOL saveEquipmetFieldRecord = [[YWMissionManager shareManager] updateEquipmentFieldRecords:equipmentFields];
            
            BOOL savePicturesToDB = [[YWResourceManager shareManager] savePicturesToDBWithArray:pictures];
            if (saveMission && saveMaintenanceRecord && savePicturesToDB && saveEquipmetFieldRecord) {
                [self.HUD hide:YES];
                //提交记录
                [[YWDetectAndUpkeepManager alloc] startUploadDetectAndUpkeepRecords:record?@[record]:nil maintenanceMission:maintenanceMission pictures:pictures];
                
            }else {
                [self.HUD hide:YES];
                YWLog(@"保存数据库失败");
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextSubmitTaskFail, nil)];
            }
        }];
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCommitSuccess, nil)];
        [self.navigationController popViewControllerAnimated:YES];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (YWMaintenanceMission*)createTempMaintenanceMissionWithType:(YWMaintenanceType)maintenanceType{
    YWMaintenanceMission *maintenanceMission = [[YWMaintenanceMission alloc]init];
    maintenanceMission.missionId = -1 * [YWCommonTool randNumber];
    maintenanceMission.maintenanceTypeId = maintenanceType;
    maintenanceMission.missionStatus = YWMissionStatusFinished;
    
    if (maintenanceType == YWMaintenanceTypeDetection) {
        maintenanceMission.missionName = NSLocalizedString(@"tempDetectionMission", nil);//@"临时检测任务";
    }else{
        maintenanceMission.missionName = NSLocalizedString(@"tempUpkeepMission", nil);//@"临时保养任务";
    }
    maintenanceMission.equipmentQuantity = 1;
    maintenanceMission.completedQuantity = 1;
    maintenanceMission.startTime = [[NSDate date] timeIntervalSince1970] * 1000;
    maintenanceMission.createTime = maintenanceMission.startTime;
    maintenanceMission.finishTime = maintenanceMission.startTime;
    maintenanceMission.updateTime = maintenanceMission.startTime;
    maintenanceMission.cutoffTime = maintenanceMission.startTime;
    YWHandler *mySelf = [[YWHandler alloc]init];
    YWLoginUser *user = [YWLoginTool loginUser];
    mySelf.uniqueId = user.uniqueId;
    mySelf.userName = user.userName;
    mySelf.headIcon = user.headIcon;
    mySelf.mobile = user.mobile;
    maintenanceMission.creator = mySelf;
    maintenanceMission.executorIds = [@(user.uniqueId) stringValue];
    maintenanceMission.read = YES;
    
    NSInteger locationId = 0;
    if (_qrCodeId) {
        locationId = [[YWEquipmentManager shareManager]locationIdWithQrcodeId:_qrCodeId];
    }else if (_locationId){
        locationId = _locationId;
    }
    
    YWBuilding* building = [[YWBuildingManager shareManager] buildingWithLocationId:locationId];
    maintenanceMission.buildingId = building.buildingId;
    return maintenanceMission;
}

- (NSArray*)createPictureWithMission:(YWMaintenanceMission*)mission equipment:(YWEquipment*)equipment record:(YWEquipmentMaintenanceRecord*)record
{
    NSMutableArray* pictures = [NSMutableArray array];
    for (int i = 0; i < [equipment.totalImageNameArray count]; i++) {
        YWPicture* picture = [[YWPicture alloc] init];
        picture.pictureId = [YWCommonTool randStringId];
        picture.pictureName = equipment.totalImageNameArray[i];
        picture.isLocalImage = YES;
        picture.uploadStatus = YWPictureUploadStatusNull;
        picture.missionId = mission.missionId;
        picture.maintenanceType = mission.maintenanceTypeId;
        picture.equipmentId = record.equipmentId;
        picture.recordId = record.recordId;
        [pictures addObject:picture];
    }
    return pictures;
}
- (YWEquipmentMaintenanceRecord*)createEquipmentMaintenanceRecordsWithMission:(YWMaintenanceMission*)mission equipment:(YWEquipment*)equipment
{
    YWEquipmentMaintenanceRecord* maintenanceRecord = [[YWEquipmentMaintenanceRecord alloc] init];
    //这里原来有减idx  -idx（改了时间戳的方法后就删掉了）
    maintenanceRecord.recordId = [YWCommonTool negativeTimestampId] ;
    /**任务ID*/
    maintenanceRecord.missionId = mission.missionId;
    NSString *uniqueTag = [YWCommonTool randStringId];
    maintenanceRecord.maintenanceTypeId = mission.maintenanceTypeId;
    maintenanceRecord.uniqueTag = uniqueTag;
    maintenanceRecord.equipmentId = equipment.equipmentId;
    maintenanceRecord.note = [equipment.psText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    maintenanceRecord.completeTime = [[NSDate date] timeIntervalSince1970] * 1000;
    maintenanceRecord.clientScanTime = _clientScanTime;
    maintenanceRecord.handlerName = [YWLoginTool loginUser].userName;
    maintenanceRecord.status = YWEquipmentMaintenanceRecordStatusNormal;
    maintenanceRecord.uploadStatus = YWEquipmentMaintenanceRecordUploadStatusUploading;
    
    NSString *dayMonthString = [YWCommonTool showTime:maintenanceRecord.completeTime / 1000 andFormatter:KTimeFormatDayMonth];
    maintenanceRecord.dayMonthString = dayMonthString;
    //检测保养都是正常完成状态，没有故障状态
    //if (self.postTroubleRecordArray.count>0) {
    //maintenanceRecord.status = YWEquipmentMaintenanceRecordStatusTrouble;
    //}
    
    return maintenanceRecord;
}
- (NSArray*)createEquipmentFieldsRecordsWithRecord:(YWEquipmentMaintenanceRecord*)record equipment:(YWEquipment*)equipment{
    __block NSMutableArray* fieldsArray = [[NSMutableArray alloc]init];
    __block NSMutableArray* allFieldRecords = [NSMutableArray array];
    
    [equipment.runTimeParameterArray enumerateObjectsUsingBlock:^(YWRunTimeParameter*  _Nonnull field, NSUInteger cusIdx, BOOL * _Nonnull stop) {
        YWEquipmentFieldRecord *fieldRecord = [[YWEquipmentFieldRecord alloc]init];
        fieldRecord.uniqueTag = record.uniqueTag;
        fieldRecord.fieldId = field.fieldId;
        fieldRecord.fieldName = field.fieldName;
        if (field.fieldType.fieldTypeId == YWEquipmentFieldTypeIdDownSelect) {
            fieldRecord.fieldTypeId = YWEquipmentFieldTypeIdDownSelect;
            fieldRecord.fieldOption = field.fieldOptionValue;
        }else{
            fieldRecord.fieldValue = field.fieldValue;
        }
        fieldRecord.maintenanceTypeId = self.maintenanceType;
        [fieldsArray addObject:fieldRecord];
        [allFieldRecords addObject:fieldRecord];
    }];
    record.equipmentFieldRecord = fieldsArray;
    return allFieldRecords;
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextSubmitTask, nil);
        hud.dimBackground = YES;
        // hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
